package com.xxx.springboot.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 系统拦截器
 */
@Component
public class SystemInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(SystemInterceptor.class);
	
	// 在执行handler之前来执行的
	// 用于用户认证校验、用户权限校验
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.debug("enter preHandle()...");
		request.setAttribute("begin_nano_time", System.nanoTime());
		return true;
	}

	// 在执行handler返回modelAndView之前来执行
	// 如果需要向页面提供一些公用 的数据或配置一些视图信息，使用此方法实现 从modelAndView入手
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.debug("SystemInterceptor | enter postHandle()...");
		long begin_nano_time = (Long) request.getAttribute("begin_nano_time");
		long interval = System.nanoTime() - begin_nano_time;
		logger.info("SystemInterceptor | uri {} spent time(ms): {}", request.getRequestURI(), interval/1000000);
	}

	// 执行handler之后执行此方法
	// 作系统 统一异常处理，进行方法执行性能监控，在preHandle中设置一个时间点，在afterCompletion设置一个时间，两个时间点的差就是执行时长
	// 实现 系统 统一日志记录
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex)
			throws Exception {
		logger.debug("SystemInterceptor | enter afterCompletion()...");
		if (ex != null) {
			logger.error("SystemInterceptor | uri {} happend exception: {}", request.getRequestURI(), ex);
		}
	}

}
